package com.rickie.hello.webflux.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class TestController {

    @GetMapping("sync")
    public String sync() {
        log.info("同步方法启动...");
        String result = this.execute();
        log.info("同步方法结束。");
        return result;
    }

    @GetMapping("async/mono")
    public Mono<String> asyncMono() {
        log.info("异步方法启动...");
        Mono<String> result = Mono.fromSupplier(this::execute);
        log.info("异步方法结束。");
        return result;
    }

    @GetMapping("fruit")
    public Flux<String> asyncFlux() {
        log.info("Start ...");
        List<String> fruits = Arrays.asList("Apple","Orange","Grape","Banana","Strawberry");
        Flux<String> fruitFlux = Flux.fromIterable(fruits)
                .delaySubscription(Duration.ofMillis(250))
                .delayElements(Duration.ofMillis(1000));
        fruitFlux.subscribe(f -> log.info("Here's some fruit:" + f));
        log.info(" === End ===");
        return fruitFlux;
    }

    private String execute() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "hello";
    }
}
